package com.mcf.xiaolinju.controller;
import com.google.code.kaptcha.Producer;
import com.mcf.xiaolinju.entity.Code;
import com.mcf.xiaolinju.service.impl.CodeServiceImpl;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;

@RestController
@CrossOrigin
public class CodeController {
    @Resource
    private Producer producer;
    @Autowired
    CodeServiceImpl codeService;
    //将生成的验证码存入数据库中


   //生成验证码
    @RequestMapping(value = "/captcha.jpg",method = RequestMethod.GET)
    public String captcha(HttpServletResponse response, HttpServletRequest request) {

        response.setHeader("Cache-Control","no-store,no-cache");

        // 设置输出流内容格式为图片格式.image/jpeg,图片格式用于生成图片随机码
        response.setContentType("image/jpeg");

        // 生成文字验证码
        String text = producer.createText();
        // 生成图片验证码
        BufferedImage image = producer.createImage(text);
        // 保存验证码到数据库
        Date dd=new Date();
        //格式化
        LocalDateTime ldt=dd.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
        Code code1=new Code();
        code1.setCreatedate(ldt);
        code1.setNumber(text);
        codeService.save(code1);

        ServletOutputStream outputStream = null;

        try {
            outputStream = response.getOutputStream();
            ImageIO.write(image,"jpg",outputStream);
        } catch (IOException e){
            e.printStackTrace();
        }
        IOUtils.closeQuietly(outputStream);
        return text;
    }
    //得到最新的验证码
    @RequestMapping("/getCode")
    public String getCode(){
        return  codeService.selectByMaxId();
    }

}


